<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

interface ChatMessage {
  id: number;
  content: string;
  username: string;
  avatar?: string;
  isVip?: boolean;
  isFan?: boolean;
  isAdmin?: boolean;
  gift?: {
    name: string;
    count: number;
    icon?: string;
  };
  timestamp: number;
}

const props = defineProps({
  height: {
    type: Number,
    default: 300
  },
  width: {
    type: Number,
    default: 400
  },
  maxMessages: {
    type: Number,
    default: 50
  },
  autoScroll: {
    type: Boolean,
    default: true
  }
});

const chatMessages = ref<ChatMessage[]>([]);
const chatContainer = ref<HTMLElement | null>(null);
const isScrolling = ref(false);
const shouldAutoScroll = ref(props.autoScroll);

// 添加聊天消息
const addChatMessage = (content: string, options: Partial<ChatMessage> = {}) => {
  const newMessage: ChatMessage = {
    id: Date.now() + Math.random(),
    content,
    username: options.username || '游客' + Math.floor(Math.random() * 10000),
    avatar: options.avatar,
    isVip: options.isVip || false,
    isFan: options.isFan || false,
    isAdmin: options.isAdmin || false,
    gift: options.gift,
    timestamp: Date.now()
  };
  
  chatMessages.value.push(newMessage);
  
  // 控制消息数量
  if (chatMessages.value.length > props.maxMessages) {
    chatMessages.value = chatMessages.value.slice(-props.maxMessages);
  }
  
  // 自动滚动到底部
  if (shouldAutoScroll.value) {
    nextTick(() => {
      scrollToBottom();
    });
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    // 使用平滑滚动，确保滚动到底部
    chatContainer.value.scrollTo({
      top: chatContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  }
};

// 处理滚动事件
const handleScroll = () => {
  if (!chatContainer.value) return;
  
  // 检测是否滚动到底部
  const isAtBottom = chatContainer.value.scrollHeight - chatContainer.value.scrollTop <= chatContainer.value.clientHeight + 50;
  shouldAutoScroll.value = isAtBottom;
};

// 暴露方法给父组件
defineExpose({
  addChatMessage,
  scrollToBottom
});

// 生命周期钩子
onMounted(() => {
  if (chatContainer.value) {
    chatContainer.value.addEventListener('scroll', handleScroll);
  }
  
  // 测试数据
  // const testMessages = [
  //   '主播好厉害！',
  //   '666666',
  //   '这个游戏我也在玩',
  //   '主播好可爱',
  //   '关注了',
  //   '主播唱首歌吧',
  //   '这个操作太秀了',
  //   '主播玩得真好',
  //   '哈哈哈哈哈',
  //   '打call'
  // ];
  
  // const testUsernames = [
  //   '抖音用户',
  //   '快乐的小猪',
  //   '游戏达人',
  //   '音乐爱好者',
  //   '萌新求带',
  //   '老粉丝了',
  //   '路过的游客',
  //   '热心观众',
  //   '职业玩家',
  //   '小可爱'
  // ];
  
  // // 添加一些测试消息
  // const addTestMessage = () => {
  //   const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)];
  //   const randomUsername = testUsernames[Math.floor(Math.random() * testUsernames.length)] + Math.floor(Math.random() * 1000);
  //   const isVip = Math.random() > 0.85;
  //   const isFan = !isVip && Math.random() > 0.7;
  //   const isAdmin = !isVip && !isFan && Math.random() > 0.95;
  //   const hasGift = Math.random() > 0.9;
    
  //   let gift;
  //   if (hasGift) {
  //     const gifts = [
  //       { name: '爱心', count: Math.floor(Math.random() * 10) + 1 },
  //       { name: '鲜花', count: Math.floor(Math.random() * 5) + 1 },
  //       { name: '小星星', count: Math.floor(Math.random() * 99) + 1 },
  //       { name: '棒棒糖', count: Math.floor(Math.random() * 3) + 1 },
  //       { name: '火箭', count: 1 }
  //     ];
  //     gift = gifts[Math.floor(Math.random() * gifts.length)];
  //   }
    
  //   addChatMessage(randomMessage, {
  //     username: randomUsername,
  //     isVip,
  //     isFan,
  //     isAdmin,
  //     gift
  //   });
    
  //   setTimeout(addTestMessage, Math.random() * 3000 + 500);
  // };
  
  // // 开始添加测试消息
  // setTimeout(addTestMessage, 1000);
});

onUnmounted(() => {
  if (chatContainer.value) {
    chatContainer.value.removeEventListener('scroll', handleScroll);
  }
});
</script>

<template>
  <div 
    ref="chatContainer" 
    class="chat-container"
    :style="{ height: `${100}%`, width: `${100}%` }"
  >
    <div class="chat-messages">
      <div 
        v-for="message in chatMessages" 
        :key="message.id" 
        class="chat-message"
        :class="{ 
          'message-vip': message.isVip, 
          'message-fan': message.isFan && !message.isVip,
          'message-admin': message.isAdmin && !message.isVip && !message.isFan,
          'message-gift': message.gift
        }"
      >
        <div class="message-content">
          <div class="message-user">
            <img v-if="message.avatar" :src="message.avatar" class="user-avatar" />
            <div v-else class="user-avatar default-avatar">
              <!-- {{ message.username.charAt(0) }} -->
              {{ message.username }}:
            </div>
            <div class="user-info">
              <div class="username-container">
                <!-- <span class="username">{{ message.username }}</span> -->
                <!-- <span v-if="message.isVip" class="user-badge vip-badge">VIP</span>
                <span v-else-if="message.isFan" class="user-badge fan-badge">粉丝</span>
                <span v-else-if="message.isAdmin" class="user-badge admin-badge">管理员</span> -->
              </div>
              
              <div v-if="message.gift" class="gift-info">
                <!-- <span class="gift-text">送出了 {{ message.gift.count }} 个{{ message.gift.name }}</span> -->
                 <span class="gift-text">送出了 {{ message.gift.name }} ×{{ message.gift.count }}</span>
                <img v-if="message.gift.icon" :src="message.gift.icon" class="gift-icon" />
              </div>
              <div v-else class="message-text">{{ message.content }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="!shouldAutoScroll" class="new-message-indicator" @click="scrollToBottom">
      <span>新消息</span>
      <div class="arrow-down"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  position: relative;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: transparent;
  padding: 10px 0;
  box-sizing: border-box;
  
  &::-webkit-scrollbar {
    width: 5px;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 3px;
  }
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-message {
  animation: fadeIn 0.3s ease-in-out;
  max-width: 100%;
  
  .message-content {
    padding: 8px;
    border-radius: 8px;
    background-color: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(5px);
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .message-user {
    display: flex;
    align-items: flex-start;
    
    .user-avatar {
      // width: 24px;
      height: 24px;
      // border-radius: 50%;
      margin-right: 8px;
      flex-shrink: 0;
    }
    
    .default-avatar {
      // background: linear-gradient(45deg, #3498db, #8e44ad);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      // font-weight: bold;
      color: #FFCF3E;
    }

    
    .user-info {
      flex: 1;
      min-width: 0;
    }
    
    .username-container {
      display: flex;
      align-items: center;
      margin-bottom: 2px;
      flex-wrap: wrap;
    }
    
    .username {
      font-size: 12px;
      font-weight: 500;
      color: #fff;
      margin-right: 5px;
      max-width: 120px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .user-badge {
      font-size: 10px;
      padding: 1px 4px;
      border-radius: 2px;
      margin-right: 4px;
    }
    
    .vip-badge {
      background-color: #FFD700;
      color: #000;
    }
    
    .fan-badge {
      background-color: #00BFFF;
      color: #fff;
    }
    
    .admin-badge {
      background-color: #FF4500;
      color: #fff;
    }
    
    .message-text {
      font-size: 14px;
      color: #fff;
      word-break: break-word;
      line-height: 1.4;
    }
    
    .gift-info {
      display: flex;
      align-items: center;
      color: #FFD700;
      font-size: 14px;
      
      .gift-text {
        margin-right: 5px;
      }
      
      .gift-icon {
        width: 16px;
        height: 16px;
      }
    }
  }
}

.message-vip .message-content {
  background: linear-gradient(90deg, rgba(255, 215, 0, 0.3), rgba(0, 0, 0, 0.4));
  border-left: 3px solid #FFD700;
}

.message-fan .message-content {
  background: linear-gradient(90deg, rgba(0, 191, 255, 0.3), rgba(0, 0, 0, 0.4));
  border-left: 3px solid #00BFFF;
}

.message-admin .message-content {
  background: linear-gradient(90deg, rgba(255, 69, 0, 0.3), rgba(0, 0, 0, 0.4));
  border-left: 3px solid #FF4500;
}

.message-gift .message-content {
  background: linear-gradient(90deg, rgba(255, 215, 0, 0.2), rgba(0, 0, 0, 0.4));
  border: 1px solid rgba(255, 215, 0, 0.3);
}

.new-message-indicator {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  animation: pulse 1.5s infinite;
  
  .arrow-down {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid white;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    opacity: 0.7;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.7;
  }
}
</style>